package cn.wk.user.controller;

import cn.wk.basic.constant.ConstantWechat;
import cn.wk.basic.utils.AjaxResult;
import cn.wk.user.domain.LoginInfo;
import cn.wk.user.domain.dto.LoginInfoDto;
import cn.wk.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private IWechatService wechatService;
    /**
     * 去拉取二维码
     * @return 重定向到微信的接口
     */
    @RequestMapping("/goLogin")
    public String goLogin(){
        String codeUrl = ConstantWechat.CODE_URL.replace("APPID", ConstantWechat.APPID).replace("REDIRECT_URI"
                , ConstantWechat.REDIRECT_URI);
        return "redirect:"+codeUrl;
    }

    /**
     * 二维码扫描成功后跳转到此接口
     * 然后携带code重定向至前台的Callback页面
     * @return
     */
    @RequestMapping("/callback")
    public String goCallback(String code){
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }

    /**
     * 通过前端传进来的code去获取token和其他业务
     * @param map
     * @return
     */
    @PostMapping("/getToken")
    @ResponseBody
    public AjaxResult getToken(@RequestBody Map<String,String> map){
        System.out.println(map.get("code"));
        try{
            Map<String, Object> wechat = wechatService.getToken(map.get("code"));
            return new AjaxResult().setResultObj(wechat);
        }catch(Exception e){
            return new AjaxResult(e.getMessage());
        }
    }

    /**
     * 进行微信与手机号的绑定
     * @param loginInfoDto
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult theBinding(@RequestBody LoginInfoDto loginInfoDto){
        System.out.println(loginInfoDto);
        try{
            Map<String,Object> map = wechatService.theBinding(loginInfoDto);
            return new AjaxResult().setResultObj(map);
        }catch(Exception e){
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }
}
